package com.allenkerr.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.mongodb.WriteResult;

import com.allenkerr.common.SequenceException;
import com.allenkerr.dao.SequenceRepository;
import com.allenkerr.dao.TodoRepository;
import com.allenkerr.dao.TodoRepositoryCustom;
import com.allenkerr.model.Todo;

/**
 * Created by 小柯 on 17.8.27 15:14.
 */
public class TodoRepositoryImpl implements TodoRepositoryCustom {

  @Autowired
  private SequenceRepository sequenceDao;
  @Autowired
  private TodoRepository todoDao;
  @Autowired
  private MongoTemplate mongoTemplate;

  @Override
  public int update(Query query, Update update) {
    WriteResult writeResult = mongoTemplate.updateFirst(query, update, Todo.class);
    return writeResult != null ? writeResult.getN() : 0;
  }

  @Override
  public Todo saveOne(Todo todo2Save) throws SequenceException {
    if (todo2Save == null) {
      return null;
    }
    long id = sequenceDao.getNextSequence(Todo.COLLECTION_NAME);
    todo2Save.setId(id);
    return todoDao.save(todo2Save);
  }
}
